<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-fill-left.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python," />





  <link rel="alternate" href="/atom.xml" title="我的笔记本" type="application/atom+xml" />






<meta name="description" content="导读既然我们完成了基本的链表功能，相信也对Python语言有了一定的了解。那么我们现在开始进阶：Python聊天室（命令行版）。">
<meta property="og:type" content="article">
<meta property="og:title" content="python进阶训练：聊天室">
<meta property="og:url" content="https://sakebow.github.io/2020/08/20/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E8%BF%9B%E9%98%B6%E8%AE%AD%E7%BB%83%EF%BC%9A%E8%81%8A%E5%A4%A9%E5%AE%A4/index.html">
<meta property="og:site_name" content="我的笔记本">
<meta property="og:description" content="导读既然我们完成了基本的链表功能，相信也对Python语言有了一定的了解。那么我们现在开始进阶：Python聊天室（命令行版）。">
<meta property="article:published_time" content="2020-08-19T16:01:00.000Z">
<meta property="article:modified_time" content="2020-11-01T15:28:32.071Z">
<meta property="article:author" content="sakebow">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://sakebow.github.io/2020/08/20/python/老兵新练/python进阶训练：聊天室/"/>



<meta name="google-site-verification" content="gmKmVpWaqN85ipDFNNCd2AweYJjcTFrVxCKCy36wueo" />
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?1d2c90caa02c073d8ebaa116ab3027fb";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


  <title>python进阶训练：聊天室 | 我的笔记本</title>
  








  
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript" src="/js/src/custom.js"></script>
  
<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/sakebow" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub">
	  <svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"
	    style="fill:#64CEAA; color:#fff; position: fixed; top: 0; border: 0; right: 0; z-index: 999;">
	    <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
		<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
		  fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
		<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
		  fill="currentColor" class="octo-body"></path>
	  </svg>
	</a>
	<style>
	  .github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}
	  @keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}
	  @media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}
	</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一只干什么都会失败但是很不想放弃的科研狗</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sakebow.github.io/2020/08/20/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E8%BF%9B%E9%98%B6%E8%AE%AD%E7%BB%83%EF%BC%9A%E8%81%8A%E5%A4%A9%E5%AE%A4/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sakebow">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/icon/UN.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python进阶训练：聊天室</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-08-20T00:01:00+08:00">
                2020-08-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%BC%96%E7%A8%8B%E8%BF%9B%E9%98%B6%E7%BB%BC%E5%90%88%E6%B5%8B%E9%AA%8C/" itemprop="url" rel="index">
                    <span itemprop="name">编程进阶综合测验</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/08/20/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E8%BF%9B%E9%98%B6%E8%AE%AD%E7%BB%83%EF%BC%9A%E8%81%8A%E5%A4%A9%E5%AE%A4/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2020/08/20/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E8%BF%9B%E9%98%B6%E8%AE%AD%E7%BB%83%EF%BC%9A%E8%81%8A%E5%A4%A9%E5%AE%A4/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.7k字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="导读"><a href="#导读" class="headerlink" title="导读"></a>导读</h2><p><strong>既然我们完成了基本的链表功能，相信也对<code>Python</code>语言有了一定的了解。那么我们现在开始进阶：<code>Python</code>聊天室（命令行版）。</strong></p>
<a id="more"></a>
<h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><p>使用<code>UDP</code>代码库，使得两个进程之间得以通信。接收的时候直接输出到终端；发送的时候直接发送到指定端口，并使用死循环监听信息。</p>
<h2 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 定义全局变量udp</span></span><br><span class="line">udp = socket(AF_INET, SOCK_DGRAM)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 发送数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">send_data</span><span class="params">(send_data, target_ip)</span>:</span></span><br><span class="line">  udp.sendto(send_data.encode(encoding = <span class="string">'utf-8'</span>), target_ip)</span><br><span class="line">  <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 接受数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">recv_data</span><span class="params">()</span>:</span></span><br><span class="line">  <span class="comment"># 拿到传输数据和源地址</span></span><br><span class="line">  socket_data, addr = udp.recvfrom(<span class="number">1024</span>)</span><br><span class="line">  <span class="comment"># 当前时间</span></span><br><span class="line">  current_time = time.strftime(<span class="string">'%Y-%m-%d %X'</span>, time.localtime(time.time()))</span><br><span class="line">  print(<span class="string">'================================================='</span>)</span><br><span class="line">  <span class="comment"># 输出到终端</span></span><br><span class="line">  print(<span class="string">f'now: <span class="subst">&#123;current_time&#125;</span>, IP: <span class="subst">&#123;addr[<span class="number">0</span>]&#125;</span>:<span class="subst">&#123;addr[<span class="number">1</span>]&#125;</span>\ncontent: <span class="subst">&#123;socket_data.decode(encoding = <span class="string">"utf-8"</span>)&#125;</span>'</span>)</span><br><span class="line">  print(<span class="string">'================================================='</span>)</span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>最后，我们在主函数中使用死循环监听这两个函数就好了：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">  <span class="comment"># 客户端1用8998端口</span></span><br><span class="line">  addr_bind = (<span class="string">''</span>, <span class="number">8998</span>)</span><br><span class="line">  udp.bind(addr_bind)</span><br><span class="line">  <span class="comment"># 客户端2用8999端口 / 本机IP192.168.1.111</span></span><br><span class="line">  target_ip = (<span class="string">'192.168.1.111'</span>, <span class="number">8999</span>)</span><br><span class="line">  <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    send_text = input(<span class="string">'say something: '</span>)</span><br><span class="line">    <span class="keyword">if</span> send_text == <span class="string">'bye'</span>:</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="comment"># 客户端1 - 先发送再接收</span></span><br><span class="line">    <span class="comment"># 客户端2 - 先接收再发送</span></span><br><span class="line">    send_data(send_text, target_ip)</span><br><span class="line">    recv_data()</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>到这里，简单的聊天室就完成了。</p>
<h2 id="结束？"><a href="#结束？" class="headerlink" title="结束？"></a>结束？</h2><p>你以为这样就能交作业了吗？<strong>还早着呢</strong>。这样只能实现两个端的交流，而且还只能限定从客户端1开始，从客户端2结束。作为多对多的<code>UDP</code>觉得自己非常吃亏，而且没有<code>GUI</code>的项目就不是一个好项目。</p>
<p>所以，在这里划一条线，我们将认真开始。</p>
<hr>
<h2 id="进阶1-添加服务器"><a href="#进阶1-添加服务器" class="headerlink" title="进阶1 - 添加服务器"></a>进阶1 - 添加服务器</h2><p><strong>前排提示</strong>：所有的文件都将放到<a href="https://github.com/sakebow/python-chat" target="_blank" rel="noopener"><code>GitHub</code></a>上，不会在这里花很多篇幅展示。所以希望学习的同学们可以两边结合起来看。</p>
<h3 id="综述"><a href="#综述" class="headerlink" title="综述"></a><strong>综述</strong></h3><p>就拿我们最常用的<strong>QQ</strong>和<strong>微信</strong>来说，都是由腾讯提供服务器，我们交流的时候首先提交到服务器上，然后再由服务器回显到各个客户端中。</p>
<p>所以，我们的首要目标就是<strong>建立服务器</strong>并让客户端和服务器能够<strong>正常连接</strong>。</p>
<p>首先我们需要明确服务器的功能。每次有数据提交到服务器的时候，服务器其实没有<strong>长期保留</strong>这个数据的必要，只不过是拿到了数据，并<strong>转发</strong>给所有的客户端而已。所以，实际上服务器只是需要做到<strong>接收</strong>和<strong>发送</strong>两个功能就足够了。</p>
<p>于是，这个项目的架构就差不多定下来了：</p>
<p>/ 根目录</p>
<p>┣ <code>config.py</code> 项目配置文件</p>
<p>┣ <code>ssocket.py</code> 基础socket实现类</p>
<p>┣ <code>server.py</code> 服务器实例类和功能实现</p>
<p>┣ <code>wrapper.py</code> 数据帧封装类</p>
<p>┗ <code>test.py</code> 输出测试类</p>
<p>看起来没什么毛病。就算有毛病估计你现在也是一脸蒙。接下来我将详细展开每个文件是干什么。</p>
<p>那么我们就开始准备了。既然是服务器的实现，那么就需要完善基本的网络通信，即<code>socket</code>库的具体业务实现。</p>
<h3 id="步骤一：确定基本配置项和底层实现方法"><a href="#步骤一：确定基本配置项和底层实现方法" class="headerlink" title="步骤一：确定基本配置项和底层实现方法"></a><strong>步骤一：确定基本配置项和底层实现方法</strong></h3><p><code>Python</code>的<code>socket</code>库和<code>C</code>语言的<code>socket</code>库有着异曲同工之妙，如果是使用<code>Ubuntu</code>系统编程的话应该能够很明显地感觉到这两者几乎很多都是相同的，只不过是再封装而已。发送就是<code>send()</code>，接收就是<code>recv()</code>。即：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> socket</span><br><span class="line">soc = socket()</span><br><span class="line"><span class="comment"># 发送 / 开辟大小为1024B的缓冲区，并对发送的Python对象使用*utf-8*编码为二进制数据</span></span><br><span class="line">soc.send(<span class="number">1024</span>).encode(<span class="string">'utf-8'</span>)</span><br><span class="line"><span class="comment"># 接收 / 开辟大小为1024B的缓冲区，并对接收的二进制数据使用*utf-8*解码为Python对象</span></span><br><span class="line">soc.recv(<span class="number">1024</span>).decode(<span class="string">'utf-8)</span></span><br></pre></td></tr></table></figure>
<p>看起来没什么问题。但是如果就这么写进项目中，每次收发都这么写绝对很累赘，大量重复的<code>utf-8</code>和<code>1024</code>，如果有一天需要修改的话将会是一场恶梦。</p>
<p><strong>所以新建<code>config.py</code>记录配置。</strong></p>
<p>这里需要说明的是，如果是这么定义：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 这是作为配置项很不*方便*的写法，仅供参考，请勿模仿</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SOCKET_CONFIG</span><span class="params">(object)</span>:</span></span><br><span class="line">  SOCKET_MAX_CACHE = <span class="number">1232896</span> <span class="comment"># 2的20次方</span></span><br><span class="line">  SOCKET_CHARSET_ENCODING = <span class="string">'utf-8'</span></span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>这样的话你的<code>SOCKET_MAX_CACHE</code>和<code>SOCKET_CHARSET_ENCODING</code>都被<code>Python</code>记为私有变量，不可访问。需要画很多时间构建<code>getter</code>和<code>setter</code>。虽然可以使用<code>@property</code>简化，但是需要我们手动编辑，而且我在<code>Ubuntu2004</code>中使用<code>VScode</code>直接编译不通过，他有自己的想法。所以我放弃了<code>@property</code>并选择了使用<strong>枚举类型</strong>简化：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> enum <span class="keyword">import</span> Enum</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SOCKET_CONFIG</span><span class="params">(Enum)</span>:</span> <span class="comment"># 继承Enum枚举类，属性直接用</span></span><br><span class="line">  SOCKET_MAX_CACHE = <span class="number">1232896</span></span><br><span class="line">  SOCKET_CHARSET_ENCODING = <span class="string">'utf-8'</span></span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>这样的话我们在任何地方就可以直接使用：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> config <span class="keyword">import</span> * <span class="comment"># 这么引入的前提是当前文件和config.py是同级</span></span><br><span class="line">a = SOCKET_CONFIG.SOCKET_MAX_CAHCE.value </span><br><span class="line"><span class="comment"># 枚举类直接用&#123;名称.value&#125;，直接使用名称得不到值</span></span><br></pre></td></tr></table></figure>
<p><a href="https://github.com/sakebow/python-chat/blob/master/config.py" target="_blank" rel="noopener">点击这里查看config.py文件具体内容</a></p>
<p>当然，你也可以选择使用<code>yaml</code>、<code>properties</code>、<code>csv</code>、<code>json</code>和<code>xml</code>文件记录配置，这就看你愿意怎么使用了。如果想省事，直接用<code>py</code>吧；如果是想探索知识、需要构建大型项目或者说已经有一整套配置文件读取的代码库，建议使用单独的配置文件。</p>
<h3 id="步骤2：封装底层方法"><a href="#步骤2：封装底层方法" class="headerlink" title="步骤2：封装底层方法"></a><strong>步骤2：封装底层方法</strong></h3><p>使用<code>socket</code>创建专门针对某一个特定点的服务的时候，我们更倾向于使用端对端的<code>TCP/IP</code>协议，简单的说就是<strong>针对特定IP的特定端口号发送数据</strong>。根据这个定义我们就知道，需要我们确定<code>IP</code>和<code>端口号</code>，也就是在收发数据之前绑定<code>IP</code>和<code>端口号</code>。但是每一次都绑定肯定会显得累赘。</p>
<p><strong>所以我们创建<code>ssocket.py</code>封装<code>socket</code>用以绑定基本信息</strong></p>
<p>其中创建了继承自<code>socket.socket</code>的<code>ServerSocket</code>类，使用<code>AF_INET</code>协议（<code>TCP/IP</code>协议簇中的<code>IPv4</code>协议）和<code>SOCK_STREAM</code>（<code>TCP</code>流，即使用可靠的、端对端的连接进行通信；与之对应的是<code>SOCK_DGRAM</code>，是<code>UDP</code>流，不可靠的、多对多的连接进行通信）。</p>
<p>接着，我们使用<code>socket.bind()</code>方法传入<code>IP</code>信息和<code>端口号</code>。是以<strong>元组</strong>的形式传入的，即：<code>socket.bind((&#39;127.0.0.1&#39;, 8080))</code>。</p>
<p>最后，打开监听：<code>socket.listen(128)</code>。</p>
<p><a href="">点击这里查看ssocket.py文件具体内容</a></p>
<p>有了这个准备好的<code>ServerSocket</code>，我们就能开始准备<code>Server</code>实体类了。</p>
<p>在这里插入一个小技巧：</p>
<p><em><code>Server</code>类其实没有必要继承<code>ServerSocket</code>类，因为可以在<code>Server</code>类中使用<code>ServerSocket</code>对象；当然也可以继承，因为两者在本质上就是对<code>socket</code>进行操作，<code>Server</code>完全可以继承<code>ServerSocket</code>的操作，并在类内对<code>ServerSocket</code>进行拓展。</em></p>
<p>由于一个小项目，所以就不弄那么复杂了。直接使用实例化对象。</p>
<p><strong>所以接下来新建<code>server.py</code>，编辑<code>Server</code>类</strong></p>
<h3 id="步骤三：如何启动服务器"><a href="#步骤三：如何启动服务器" class="headerlink" title="步骤三：如何启动服务器"></a><strong>步骤三：如何启动服务器</strong></h3><p>定义了类之后，我们就需要开始定义具体的服务了。用过<code>Tomcat</code>的应该都知道，我们在配环境的时候会使用<code>startup</code>语句，所以我们这里也定义一个启动服务的<code>start</code>方法。</p>
<p>具体我们需要做什么呢？因为我们的监听已经开启了，所以我们需要做的就是等待客户端的连接，即使用<code>socket.accept()</code>方法获得两个返回值，一个是从客户端发送过来的数据帧，另一个则是数据源，也就是<strong>IP地址</strong>和<strong>端口号</strong>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">soc, addr = socket.accept()</span><br><span class="line"><span class="comment"># soc是包含了此次传输的内容二进制编码等很多种数据的套接字</span></span><br><span class="line"><span class="comment"># addr则是数据源，是个元组，addr[0]是IP，addr[1]是端口号</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 拿到套接字我们可以顺势接收发送的数据，也能返回对套接字的响应</span></span><br><span class="line">print(soc.recv(<span class="number">1024</span>).decode(<span class="string">'utf-8'</span>)) <span class="comment"># 打印是为了查看是否正常</span></span><br><span class="line">soc.send(<span class="string">"hello world!"</span>.encode(<span class="string">'utf-8'</span>))</span><br></pre></td></tr></table></figure>
<p>当然，还是一样的问题：每次都这么做要重复太多的<code>utf-8</code>和<code>1024</code>，所以封装起来。</p>
<p><strong>所以我们新建<code>wrapper.py</code>封装客户端套接字</strong></p>
<p>由于我们之前已经将缓冲区大小、默认编码封装在了<code>config.py</code>里面，所以直接拿来使用：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">recv_data</span><span class="params">(self)</span>:</span></span><br><span class="line">  <span class="keyword">return</span> socket.recv(SOCKET_CONFIG.SOCKET_MAX_CACHE.value).decode(SOCKET_CONFIG.SOCKET_CHARSET_ENCODING.value)</span><br><span class="line">  <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">send_data</span><span class="params">(self, message)</span>:</span></span><br><span class="line">  <span class="keyword">return</span> socket.send(message.encode(SOCKET_CONFIG.SOCKET_CHARSET_ENCODING.value))</span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>为了保证使用之后还能够关闭<code>socket</code>以释放资源，最后再加上一个关闭的方法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">socket.close()</span><br></pre></td></tr></table></figure>
<p><a href="https://github.com/sakebow/python-chat/blob/master/wrapper.py" target="_blank" rel="noopener">点击这里查看wrapper.py文件内容</a></p>
<p>有了<code>wrapper</code>封装之后，我们就直接在<code>Server</code>类中使用<code>wrapper.py</code>定义的实例化对象，这里我定义的是<code>SocketWrapper</code>类，所以<code>Server</code>类在使用<code>accept</code>方法获得套接字后这么使用：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">soc, addr = socket.accept()</span><br><span class="line">client_soc = SocketWrapper(soc)</span><br></pre></td></tr></table></figure>
<p>针对单个客户端的单次接入，我们直接使用我们封装好的<code>client_soc</code>就好了。因为是服务器，所以是先<strong>接收</strong>来自客户端的信息，再发送回显给客户端。最后，使用<code>wrapper,py</code>中封装好的<code>close</code>方法关闭连接释放资源。</p>
<p>具体来说就是这样：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 严重警告：此处的完整代码仅展示用，有缺陷，请勿模仿</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start</span><span class="params">(self)</span>:</span></span><br><span class="line">  <span class="comment"># 获得数据和数据源</span></span><br><span class="line">  soc, addr = self.server_socket.accept()</span><br><span class="line">  <span class="comment"># 绑定封装好的IP和端口，并开启监听</span></span><br><span class="line">  client_soc = SocketWrapper(soc)</span><br><span class="line">  <span class="comment"># 输出查看数据是否正确</span></span><br><span class="line">  print(client_soc.recv_data())</span><br><span class="line">  <span class="comment"># 回显客户端</span></span><br><span class="line">  client_soc.send_data(<span class="string">'connection established!'</span>)</span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>看起来没有问题，但是这样子一个客户端发完一条信息之后，整个服务进程都结束了，再也不能接收客户端传来的消息，除非重启服务器。每条信息都要重启服务器的话也实在是太反人类了。所以我们需要服务器一直在线，那么就加上一个死循环：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 严重警告：此处的完整代码仅展示用，有缺陷，请勿模仿</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start</span><span class="params">(self)</span>:</span></span><br><span class="line">  <span class="comment"># 获得数据和数据源</span></span><br><span class="line">  soc, addr = self.server_socket.accept()</span><br><span class="line">  <span class="comment"># 绑定封装好的IP和端口，并开启监听</span></span><br><span class="line">  client_soc = SocketWrapper(soc)</span><br><span class="line">  <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    <span class="comment"># 输出查看数据是否正确</span></span><br><span class="line">    print(client_soc.recv_data())</span><br><span class="line">    <span class="comment"># 回显客户端</span></span><br><span class="line">    client_soc.send_data(<span class="string">'connection established!'</span>)</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>好了，客户端能够一直发信息了。</p>
<p>但是，这依然不够。这可是聊天室，客户端连接到服务器之后直接使用主进程的死循环收发信息，这样必然导致其他的<strong>任何客户端都不能和服务器交互</strong>，相当于莫名其妙的全员禁言了。这可要不得。</p>
<p>如果是以前用过<code>SpringBoot</code>开发<code>Web</code>的话，应该非常熟悉<code>@Asyn</code>这个注解，也就是使用子进程实现来自<code>Controller</code>的请求、调用<code>Service</code>的方法、操作<code>Dao</code>的接口等等。为何不借鉴一下这种思想呢？</p>
<p>所有的客户端一旦接入服务器便立马开启新的子进程，让所有的交互在子进程中完成。这样的话，主进程就可以完完全全地监听信息的接入，就像是<strong>前台接待</strong>一样，全权负责将到店的客户送到指定的房间（<em>子进程</em>）中。这就完成了<code>Server</code>的最终版。</p>
<p><a href="https://github.com/sakebow/python-chat/blob/master/server.py" target="_blank" rel="noopener">点击这里查看server.py文件具体内容</a></p>
<p>最后，我们来测试一下结果如何。</p>
<p><strong>这里就新建<code>test.py</code>来模拟客户端发送<code>socket</code>到服务器</strong></p>
<p><a href="https://github.com/sakebow/python-chat/blob/master/test.py" target="_blank" rel="noopener">点击这里查看<code>test.py</code>文件内容</a></p>
<p>到这里，这个聊天室就能够支持多个客户端收发信息、服务器处理多个请求了。但是他依然存在一个问题：<strong>不能显示其他人发送的信息</strong>。</p>
<p>而给其他人发送信息则又必须使用<code>socket</code>给其他<code>IP</code>发送消息。可是服务器一次只能处理一个请求，这就导致<strong>每次处理的时候只能弄到一个<code>IP</code>地址</strong>。虽然你可以写在文件里，但是这就把一个小项目写复杂了，也因为增加了硬盘的<code>IO</code>而大大降低了速度。所以，为了能够将速度发挥到极致，我这里使用<strong>单线程多路复用</strong>的<code>redis</code>来保存<strong>注册的用户信息</strong>和<strong>登录的用户信息</strong>。你可能会想这不是一样的么？<strong>实际上不一样</strong>。因为登录信息是需要写在当前在线人数表中的，同时服务器也只能给当前在线的人发送信息，否则给不在线的用户发送信息时会因为连接未建立<strong>给每个人抛了个错</strong>，结果所有在线的人一脸蒙逼地给不在线的人背锅。这明显不合理。</p>
<p>当然，还有一个优点就是<code>redis</code>还能当非关系型数据库使用，可以用于聊天记录的保存。这就是后话了。</p>
<p>那么问题来了，既然需要<code>redis</code>就需要服务器跑起来。所以这里就使用<code>Docker</code>运行一个简单的<code>redis</code>服务器。</p>
<p>首先准备<code>docker-compose.yml</code>文件，用于<code>docker</code>镜像的构建：</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">version:</span> <span class="string">'3'</span></span><br><span class="line"><span class="attr">services:</span></span><br><span class="line">  <span class="attr">redis-30xx:</span> <span class="comment"># 因为端口号不好记，所以记录端口号前两位到三位</span></span><br><span class="line">    <span class="attr">image:</span> <span class="string">'redis:latest'</span></span><br><span class="line">    <span class="attr">restart:</span> <span class="string">always</span></span><br><span class="line">    <span class="attr">hostname:</span> <span class="string">'redis-30xx'</span> <span class="comment"># 方便以后避开这些端口号，名字也改改</span></span><br><span class="line">    <span class="attr">ports:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">'3079:6379'</span> <span class="comment"># 使用30xx端口映射默认的6379</span></span><br><span class="line">    <span class="attr">volumes:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">/usr/local/docker/redis/config:/conf</span> <span class="comment"># 配置文件</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">/usr/local/docker/redis/data:/data</span> <span class="comment"># 数据文件</span></span><br></pre></td></tr></table></figure>
<p>然后在你的<code>Ubuntu</code>系统下使用超管权限运行<code>docker-compose up -d</code>，这样你的<code>redis</code>就启动起来了。</p>
<p>这里由于需要操作两个用户组，所以使用<code>redis</code>的集合和<code>python</code>的集合相对应，都是<code>sadd</code>方法用于添加用户，应用在登录和注册上；而<code>srem</code>用于移除用户，应用在用户注销上。</p>
<h2 id="进阶2-GUI"><a href="#进阶2-GUI" class="headerlink" title="进阶2 - GUI"></a>进阶2 - <code>GUI</code></h2><p>这里就直接使用<code>PyQT</code>作为<code>GUI</code>的搭建。虽然有<code>Qt Creator</code>用来简便绘制用户界面，但是底层却是<code>C++</code>。为了保证这个教程不掺杂一点与<code>Python</code>无关的东西，并为了能够让<code>Python</code>体现出网络编程中标准库的便捷性，这里直接使用一整套<code>Python</code>解决方案。</p>
<p>既然我们用的最熟悉的是QQ和微信，那么我们就干脆模仿微信的界面。当然，因为技术原因不能很好的模仿，所以就干脆就作出一点点小小的改变。不会很离谱，但也相当乱来。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>代码滞销，救救码农</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/wechatpay.png" alt="sakebow 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/alipay.jpg" alt="sakebow 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    sakebow
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://sakebow.github.io/2020/08/20/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E8%BF%9B%E9%98%B6%E8%AE%AD%E7%BB%83%EF%BC%9A%E8%81%8A%E5%A4%A9%E5%AE%A4/" title="python进阶训练：聊天室">https://sakebow.github.io/2020/08/20/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E8%BF%9B%E9%98%B6%E8%AE%AD%E7%BB%83%EF%BC%9A%E8%81%8A%E5%A4%A9%E5%AE%A4/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"> <i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/08/17/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E5%9F%BA%E7%A1%80%E7%BB%BC%E5%90%88%EF%BC%9A%E9%93%BE%E8%A1%A8/" rel="next" title="python基础综合：链表">
                <i class="fa fa-chevron-left"></i> python基础综合：链表
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/09/15/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%AE%97%E6%B3%95%E6%A8%A1%E5%9E%8B/%E9%81%97%E4%BC%A0%E7%AE%97%E6%B3%95/" rel="prev" title="遗传算法">
                遗传算法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>
	<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
    <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
	<script>
      var gitment = new Gitment({
        id: '<%= page.date %>',
        owner: 'sakebow',
        repo: 'git@github.com:sakebow/sakebow.github.io.git',
        oauth: {
          client_id: '5c74c5e1b67e5a5adbdf',
          client_secret: '0d352353407a32cee695d8ac619108e725919c57',
        },
      });
      gitment.render('gitment-container');
    </script>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/icon/UN.png"
                alt="sakebow" />
            
              <p class="site-author-name" itemprop="name">sakebow</p>
              <p class="site-description motion-element" itemprop="description">哪怕是狗也不想随随便便放弃看到的骨头</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">70</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sakebow" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sakebowljx@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/sakebow" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i>Google</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/sakebow" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/sakebow" title="Sakebow的GitHub" target="_blank">Sakebow的GitHub</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.appgofast.com" title="我喜欢的VPN" target="_blank">我喜欢的VPN</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#导读"><span class="nav-number">1.</span> <span class="nav-text">导读</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原理"><span class="nav-number">2.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#代码实现"><span class="nav-number">3.</span> <span class="nav-text">代码实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结束？"><span class="nav-number">4.</span> <span class="nav-text">结束？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#进阶1-添加服务器"><span class="nav-number">5.</span> <span class="nav-text">进阶1 - 添加服务器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#综述"><span class="nav-number">5.1.</span> <span class="nav-text">综述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#步骤一：确定基本配置项和底层实现方法"><span class="nav-number">5.2.</span> <span class="nav-text">步骤一：确定基本配置项和底层实现方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#步骤2：封装底层方法"><span class="nav-number">5.3.</span> <span class="nav-text">步骤2：封装底层方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#步骤三：如何启动服务器"><span class="nav-number">5.4.</span> <span class="nav-text">步骤三：如何启动服务器</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#进阶2-GUI"><span class="nav-number">6.</span> <span class="nav-text">进阶2 - GUI</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Sakebow</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'sakebow',
            repo: 'git@github.com:sakebow/sakebow.github.io.git',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '0d352353407a32cee695d8ac619108e725919c57',
            
                client_id: '5c74c5e1b67e5a5adbdf'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
 
</body>
</html>
